package org.example.study4;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用显式锁（ReentrantLock）保护共享资源
 */
public class Demo_411 {
    public static void main(String[] args) throws InterruptedException {
        Counter411 counter = new Counter411();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("count = " + counter.getCount());
    }
}

class Counter411 {
    private int count = 0;
    private final ReentrantLock lock = new ReentrantLock(); // 显式锁

    public void increase() {
        lock.lock(); // 手动加锁
        try {
            count++;
        } finally {
            lock.unlock(); // 必须保证解锁
        }
    }

    public int getCount() {
        return count;
    }
}
// 运行结果：count = 100000